/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.database.tables;

import com.chipchip.database.DBManager;
import com.chipchip.database.objects.DOMapResult;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 *
 * @author Tri
 */
public class DTMapResult {
    private static DTMapResult instance = null;
    public static DTMapResult sharedInstance() {
       if(instance == null) {
           instance = new DTMapResult();
       }
       return instance;
    }
    public static final String TABLE_NAME = "MapResult";
    MongoOperations m_mongoOperations;
    private DTMapResult() {
        m_mongoOperations = DBManager.sharedInstance().mongoOperations();
    }
    
    public void insert(DOMapResult mapResult) {
        m_mongoOperations.save(mapResult, TABLE_NAME);
    }
    
    public boolean delete(String mapID) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOMapResult.KEY_MAP_ID).is(mapID));
        
        DOMapResult result = m_mongoOperations.findOne(query, DOMapResult.class);
        if(result != null) {
            m_mongoOperations.remove(result);
            return true;
        }
        
        return false;
    }
    
    public boolean update(DOMapResult mapResult) {
        Query query = new Query();
        query.addCriteria(Criteria.where(DOMapResult.KEY_MAP_ID).is(mapResult.getMapID()));
        
        
        Update updateQuery = new Update();
        updateQuery.set(DOMapResult.KEY_LEVEL, mapResult.getLevel());
        updateQuery.set(DOMapResult.KEY_RATING, mapResult.getRating());
        updateQuery.set(DOMapResult.KEY_SCORE, mapResult.getScore());
        
        DOMapResult resultQuery = m_mongoOperations.findOne(query, DOMapResult.class);
        if(resultQuery != null) {
            m_mongoOperations.updateFirst(query, updateQuery, DOMapResult.class);
            return true;
        }
        return false;
    }
    
    public DOMapResult getMapResult(String mapID) {
        DOMapResult mapResult = null;
        Query query = new Query();
        query.addCriteria(Criteria.where(DOMapResult.KEY_MAP_ID).is(mapID));
        mapResult = m_mongoOperations.findOne(query, DOMapResult.class);
        return mapResult;
    }
}
